/*S'exécute quand la structure HTML est chargée*/

var jcoverflip; // jCoverFlip object (slider + wrapper)
var flip; // slider only
var jcoverflipButton; // Button added to the player that show / hide the slider
var mediaElementJS; // Player
var timestampArray; // Array that contains all the timestamps (in seconds) of all the keyframes
var parentVideoSrc = new Array(); // List of videos previously seen
var originalVideo;

window.load = new function() {
    load_player();
};

// Generate the video player and add the slider into it
function load_player() {

    // Add a button that show / hide the le slider (the action is defined in slider.js)
    MediaElementPlayer.prototype.buildslider = function(player, controls, layers, media) {
        
        jcoverflipButton = 
            $('<div id="slider-button" class="mejs-button slider-button-on">'
                + '<button type="button" aria-controls="mep_0" title="Miniatures" aria-label="Slider"></button>'
                + '</div>')
            .appendTo(controls)

            .click(function() {
                // Change the opacity of the button if the slider is enabled 
                player.options.slider = !player.options.slider;
                jcoverflipButton.toggleClass('slider-button-off slider-button-on');
                $(jcoverflip).fadeToggle(); // Show or Hide the slider when the button is clicked
            });

    };

    // Define the options of the player
    new MediaElementPlayer('#videoPlayer', {
        alwaysShowControls: true,// Hide the controls bar when the video plays
        videoVolume: 'vertical',//Audio controls orientation
        features: ['playpause', 'slider', /*'current', */'progress', 'duration', /*'tracks', */'volume', 'fullscreen'],//Ordre des controles sur la barre (et plugins)
        enableKeyboard: true,//Enable keybord shortcuts
        showTimecodeFrameCount: false, //Show the timer (##:00:00:00)
        defaultVideoWidth: 480,//Default video width
        defaultVideoHeight: 270,//Default video height
        startVolume: 0.8, //Initial volume when the player starts

        enablePluginDebug: false, //shows debug errors on screen
        mode: 'auto',/*allows testing on HTML5, flash, silverlight
                        auto: attempts to detect what the browser can do
                        auto_plugin: prefer plugins and then attempt native HTML5
                        native: forces HTML5 playback
                        shim: disallows HTML5, will attempt either Flash or Silverlight
                        none: forces fallback view*/

        enableAutosize: true, //enables Flash and Silverlight to resize to content size
        pauseOtherPlayers: true, //when this player starts, it will pause other players
        keyActions: [],  //array of keyboard commands
        iPadUseNativeControls: false, //force iPad's native controls
        iPhoneUseNativeControls: false,  //force iPhone's native controls
        AndroidUseNativeControls: false, //force Android's native controls
        alwaysShowHours: false, //forces the hour marker (##:00:00)
        showTimecodeFrameCount: false, //show framecount in timecode (##:00:00:00)
        framesPerSecond: 25, //used when showTimecodeFrameCount is set to true
        videoWidth: -1, //if set, overrides <video width>
        videoHeight: -1, //if set, overrides <video height>
        audioWidth: 400, //width of audio player
        audioHeight: 30, //height of audio player
        loop: false, //useful for <audio> player loops

        success: function (mediaElement, domObject) { 

            mediaElementJS = mediaElement;
            
            originalVideo = mediaElementJS.src;
            
            var ressourceURL = $('#ressourceURL').attr("value");

            /*
             * The player is created, the slider (slider.js) can be added into it
             * Ajax call to get the images links
             */
            $.ajax({
                type: "GET",
                url :ressourceURL,             
                data: {"reqType" : "getJsonVideo", "src": mediaElementJS.src},
                dataType: "json",
                success: function(jsonInit) {
                    if((jsonInit != '') && (typeof jsonInit != 'undefined')) {
                        load_slider(jsonInit);
                        eventHideControls();
                        eventUpdateSlides();
                        eventResizeJcoverFlip();
//                        eventContextMenu();
//                        $("#contextMenup").appendTo($('#mep_0'));
                    }
                }
            });
        },

        error: function () { // If an error is detected
            alert('Error');
        }
     });
}

// Hide the slider when the mouse is not hover it or hover the controls bar (alwaysShowControls must be set to true)
function eventHideControls() {

	var i = null;
	$(document).mousemove(
		function() {
			if (jcoverflipButton.hasClass('slider-button-on')) {
				clearTimeout(i);
				$(jcoverflip).show();
				$('#mep_0 .mejs-controls').show();
				i = setTimeout(function() {
					if (!($(jcoverflip).is(':hover') || $(
							'#mep_0 .mejs-controls').is(':hover'))) {

						$(jcoverflip).fadeOut(300);
						$('#mep_0 .mejs-controls').fadeOut(300);
					}
				}, 3000);
			} else {
				clearTimeout(i);
				$('#mep_0 .mejs-controls').show();
				i = setTimeout(function() {
					if (!$('#mep_0 .mejs-controls').is(':hover')) {

						$('#mep_0 .mejs-controls').fadeOut(300);
					}
				}, 3000);
			}

		});

}

// Scroll the slider when the video plays (to select the thumb corresponding the current timecode)
function eventUpdateSlides() {

	mediaElementJS.addEventListener('timeupdate', function(e) {
		var j = 0;
		for (var i = 0, c = timestampArray.length; i < c; i++) {
			if (mediaElementJS.currentTime >= timestampArray[i]) {
				j = i;
			}
		}
		if(!mediaElementJS.paused) {
			$(flip).jcoverflip('current', j);
		}
				
	}, false);
}

var marginLeft = parseInt($("#wrapper").css("margin-left"));
var marginTop = parseInt($("#dockbar").css( "height" ));
// Resize the slider on enter fullscreen
function eventResizeJcoverFlip() {

	MediaElementPlayer.prototype.enterFullScreen_redifined = MediaElementPlayer.prototype.enterFullScreen;
	MediaElementPlayer.prototype.enterFullScreen = function() {
		this.enterFullScreen_redifined();
		$(jcoverflip).css("width", screen.width);
		create_jcoverflip(); // To center the miniature inside the flip
		$('#mep_0').on("contextmenu",function(e){	//define the position of right click menu when fullscreen		 
			$("#contextMenup").css({"left":(e.screenX),"top":(e.screenY)}).fadeIn();
		});
	};

	MediaElementPlayer.prototype.exitFullScreen_redifined = MediaElementPlayer.prototype.exitFullScreen;
	MediaElementPlayer.prototype.exitFullScreen = function() {
		this.exitFullScreen_redifined();
		$(jcoverflip).css("width", mediaElementJS.width);
		create_jcoverflip(); // To center the miniature inside the flip
		$('#mep_0').on("contextmenu",function(e){			 
			$("#contextMenup").css({"left":(e.pageX - marginLeft),"top":(e.pageY - 205 - marginTop)}).fadeIn();
		});
	};

}

//Go to the parent video on click to the button "Parent Video"
function goToParentVideo() {

	if(parentVideoSrc.length > 0) {
		
		// Hide the button if there is no parent
		if(parentVideoSrc.length == 1) {
			$('#buttonParentVideo').hide();
		}
		
		var src = parentVideoSrc.pop();

		if (src != '') {

			if (mediaElementJS.paused == false) {
				mediaElementJS.pause();
				$(".mejs-playpause-button").toggleClass('mejs-pause mejs-play');
			}

			mediaElementJS.setSrc(src);

			var ressourceURL = $('#ressourceURL').attr("value");

			$.ajax({
				type : "GET",
				url : ressourceURL,
				data : {
					"reqType" : "getJsonVideo",
					"src" : src
				},
				dataType : "json",
				success : function(jsonVideo) { // jsonVideo contains informations about the video that has been selected
					$('#menuSelect').replaceWith('<div id="menuSelect"></div>'); // Clean the old menu
					load_slider(jsonVideo); // Rebuild the slider with informations corresponding to the new video
				}
			});
		}
	}
}

//Go to the first video loaded on click to the button "Original Video"
function goToOrignalVideo() {

	parentVideoSrc = [];
	$('#buttonParentVideo').hide();
	
	if (mediaElementJS.paused == false) {
		mediaElementJS.pause();
		$(".mejs-playpause-button").toggleClass('mejs-pause mejs-play');
	}
	
	mediaElementJS.setSrc(originalVideo);

	var ressourceURL = $('#ressourceURL').attr("value");

	$.ajax({
		type : "GET",
		url : ressourceURL,
		data : {
			"reqType" : "getJsonVideo",
			"src" : originalVideo
		},
		dataType : "json",
		success : function(jsonVideo) { // jsonVideo contains informations about the video that has been selected
			$('#menuSelect').replaceWith('<div id="menuSelect"></div>'); // Clean the old menu
			load_slider(jsonVideo); // Rebuild the slider with informations corresponding to the new video
		}
	});

}


/************Contexte Menu*************/
//function showMenu(){
//    if( mediaElementJS.paused == true){
//        $('#contextMenup ul .play').css({"display": "block"});
//        $('#contextMenup ul .pause').css({"display": "none"});
//        
//    }else {
//        $('#contextMenup ul .play').css({"display": "none"});
//        $('#contextMenup ul .pause').css({"display": "block"});
//    }
//}
//
////create the right click menu 
//function eventContextMenu() {
//      $('#mep_0').on("contextmenu",function(e){
//          if(typeof e.preventDefault == "function"){
//                e.preventDefault();//prevent the default right-click menu
//            }else{
//                e.returnValue = false;
//            }
//          $("#contextMenup").css({"left":(e.pageX - marginLeft),"top":(e.pageY - 205 - marginTop)}).fadeIn();//define the position of right click menu        
//          showMenu();
//      });
//    $(document).bind("click",function(e){
//        var target  = $(e.target);
//        if(target.closest('#mep_0').length == 0){// hide the right click menu when we click outside of the videoPlayer
//            $("#contextMenup").hide();
//        }
//    });
//    $('#contextMenup ul .play').click(function() {
//        mediaElementJS.play();
//        $("#contextMenup").hide();
//    });
//
//    $('#contextMenup ul .pause').click(function() {
//        mediaElementJS.pause();
//        $("#contextMenup").hide();
//    });
//    
//    $('#contextMenup ul .mute').click(function() {
//        mediaElementJS.setMuted(true);
//        $("#contextMenup").hide();
//    });
//    
//    $('#contextMenup ul .first').click(function() {      
//        $('#flip').jcoverflip('first');
//        mediaElementJS.pause();
//         $("#contextMenup").hide(); 
//    });
//
//    $('#contextMenup ul .last').click(function() {      
//        $('#flip').jcoverflip('last');
//         mediaElementJS.pause();
//         $("#contextMenup").hide();
//    });
//    
//    $('#contextMenup ul .next').click(function() {
//        $(flip).jcoverflip('next', '1', false);
//        mediaElementJS.pause();
//         $("#contextMenup").hide();
//    });
//    
//    $('#contextMenup ul .previous').click(function() {
//        $(flip).jcoverflip('previous', '1', false); 
//        mediaElementJS.pause();
//         $("#contextMenup").hide();
//    });
//    
//}